首页 > 试题广场 >

设计LFU缓存结构

[编程题]设计LFU缓存结构
  • 热度指数:23499 时间限制:C/C++ 2秒,其他语言4秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
一个缓存结构需要实现如下功能。
  • set(key, value):将记录(key, value)插入该结构
  • get(key):返回key对应的value值
但是缓存结构中最多放K条记录,如果新的第K+1条记录要加入,就需要根据策略删掉一条记录,然后才能把新记录加入。这个策略为:在缓存结构的K条记录中,哪一个key从进入缓存结构的时刻开始,被调用set或者get的次数最少,就删掉这个key的记录;
如果调用次数最少的key有多个,上次调用发生最早的key被删除
这就是LFU缓存替换算法。实现这个结构,K作为参数给出

数据范围:
要求:get和set的时间复杂度都是 ,空间复杂度是


若opt=1,接下来两个整数x, y,表示set(x, y)
若opt=2,接下来一个整数x,表示get(x),若x未出现过或已被移除,则返回-1

对于每个操作2,返回一个答案
示例1

输入

[[1,1,1],[1,2,2],[1,3,2],[1,2,4],[1,3,5],[2,2],[1,4,4],[2,1]],3

输出

[4,-1]

说明

在执行"1 4 4"后,"1 1 1"被删除。因此第二次询问的答案为-1   

备注:

纯Map实现(纯粹是因为链表太长了不想看),在LRU的基础上改的,仅供参考。
/**
 * @param {number} capacity
 */
var Solution = function(capacity) {
    // write code here
    this.max = capacity;
    this.map = new Map();//保存数据的map
    this.nummap = new Map();//记录次数的map
};

/** 
 * @param {number} key
 * @return {number}
 */
Solution.prototype.get = function(key) {
    // write code here
    if(!this.map.has(key)) return -1;
    else {
        let value = this.map.get(key);
        let cnt = this.nummap.get(key)+1;
        //每访问一次重新加入,方便后续次数相同的情况找到最早访问的
        this.nummap.delete(key);
        this.nummap.set(key,cnt);
        return value;
    }
};

/** 
 * @param {number} key 
 * @param {number} value
 * @return {void}
 */
Solution.prototype.set = function(key, value) {
    // write code here
    if(this.map.has(key)){
        this.map.set(key,value);
        this.nummap.set(key,this.nummap.has(key)?this.nummap.get(key)+1:1);
     }
    else{
        if(this.map.size == this.max){
            let keys = Array.from(this.nummap.keys());
            let cnt = Infinity,tmp;
            //找到次数最小并且访问最早的
            for(let item of keys){
                if(this.nummap.get(item)<cnt){cnt=this.nummap.get(item);tmp=item;}
            }
            //同时删掉两个map中该key的数据
            this.map.delete(tmp);
            this.nummap.delete(tmp);
            
            this.map.set(key,value);
            this.nummap.set(key,this.nummap.has(key)?this.nummap.get(key)+1:1);
        }else{
            this.map.set(key,value);
            this.nummap.set(key,this.nummap.has(key)?this.nummap.get(key)+1:1);
        }
    }
};

/**
 * lfu design
 * @param operators int整型二维数组 ops
 * @param k int整型 the k
 * @return int整型一维数组
 */
function LFU( operators ,  k ) {
    // write code here
    let obj = new Solution(k);
    let res = [];
    for(let i=0;i<operators.length;i++){
        let op = operators[i];
        //进行set
        if(op[0]==1){
            obj.set(op[1],op[2]);
        }
        //进行get
        else{
            res.push(obj.get(op[1]));
        }
    }
    return res;
}
module.exports = {
    LFU : LFU
};



发表于 2022-10-30 19:11:04 回复(1)
/* 定义节点 */
class Node {
    constructor (key, value) {
        this.key = key
        this.value = value
        this.freq = 1   	// 访问频次
        this.pre = null
        this.next = null
    }
}

/* 双向链 表*/
class DualLinkedList {
    constructor (node) {
        this.head = new Node()
        this.tail = new Node()
        this.head.next = this.tail
        this.tail.pre = this.head
    }

    /* 移除 */
    remove (node) {
        node.pre.next = node.next
        node.next.pre = node.pre
    }

    /* 插入节点(head之后) */
    add (node) {
        node.next = this.head.next
        this.head.next.pre = node
        node.pre = this.head
        this.head.next = node
    }

    /* 判空 */
    isEmpty () {
        return this.head.next === this.tail && this.tail.pre === this.head
    }
}

class LFUCache {
    constructor (capacity) {
        this.capacity = capacity
        this.minFreq = 0  				// 最小使用频率,删除使用
        this.size = 0     				// 当前已使用的容量
        this.freqMap = new Map()  // freq-DualLinkedList
        this.cacheMap = new Map() // key-node
    }

    // 频率+1,freqMap的旧频率的key中移除,添加到新的freq链表中
    increaseFreq (node) {
        let list = this.freqMap.get(node.freq)
        list.remove(node)
      	// 同步更新最新频率标记(如果当前是最小频率节点)
        if (list.isEmpty() && node.freq === this.minFreq) {
            this.minFreq += 1
        }
        node.freq += 1
        let newList = this.freqMap.get(node.freq)
        if (newList === undefined) {
            newList = new DualLinkedList()
        }
        newList.add(node)	// 最新频率索引对应的双向链表中增加该节点
        this.freqMap.set(node.freq, newList)
    }
 
  	/* 获取节点 value */
    get(key) {
        let node = this.cacheMap.get(key)
        if (node === undefined) {
          	// 不存在,返回 -1
            return -1
        }
      	// 存在,返回当前节点值;同时访问频次 +1
        this.increaseFreq(node)
        return node.value
    }

   	/* 增加节点 */ 	
    put (key, value) {
        if (this.capacity === 0) return
        // 如果key已存在,则变更其值,增加访问频率
        if (this.cacheMap.has(key)) {
            let node = this.cacheMap.get(key)
            node.value = value
            this.cacheMap.set(key, node)
            this.increaseFreq(node)
            return
        }
      	// 容量达到上限
        if (this.size === this.capacity) {
          	// 获取最小频率队列(通过minFreq标记)
            let miniFreqList = this.freqMap.get(this.minFreq)
            // 获取最小频次队列的队尾(最小且最久)
            let miniFreqNode = miniFreqList.tail.pre
            // 淘汰该节点
            miniFreqList.remove(miniFreqNode)
            this.freqMap.set(this.minFreq, miniFreqList)
            this.cacheMap.delete(miniFreqNode.key)
        }

      	// 插入新节点
        let node = new Node(key, value)
        this.cacheMap.set(key, node)
    	// freq为1的链表中,插入节点
        let list = this.freqMap.get(1)
        if (list === undefined) {
            list = new DualLinkedList()
        }
        list.add(node)

        this.freqMap.set(1, list)
        this.minFreq = 1
        if (this.size < this.capacity) {
            this.size += 1
        }
        return
    }
}
/**
 * lfu design
 * @param operators int整型二维数组 ops
 * @param k int整型 the k
 * @return int整型一维数组
 */
function LFU( operators ,  k ) {
    // write code here
    const lfu = new LFUCache(k);
    let result = [];
    operators.forEach(([op, key, value]) => {
        op == 1 ? lfu.put(key, value) : result.push(lfu.get(key));
    })
    return result;
}
module.exports = {
    LFU : LFU
};

发表于 2022-10-27 15:19:18 回复(0)

问题信息

难度:
3条回答 3722浏览

热门推荐

通过挑战的用户

查看代码